package com.changdu.seatunnel.admin.config;

import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.changdu.seatunnel.admin.config.model.ExceptionResult;
import com.changdu.seatunnel.admin.config.model.ResultResponse;
import com.changdu.seatunnel.admin.util.JsonUtils;
import com.fasterxml.jackson.databind.JsonNode;

import jakarta.servlet.http.HttpServletResponse;

@SuppressWarnings("rawtypes")
@RestControllerAdvice
public class ResponseHandlerAdvice implements ResponseBodyAdvice, Ordered {

	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, 
			ServerHttpRequest request, ServerHttpResponse response) {
		if (body instanceof ExceptionResult result) {
			return result;
		}
        HttpServletResponse servletRespose = ((ServletServerHttpResponse) response).getServletResponse();
		ResultResponse<JsonNode> success = ResultResponse.success(JsonUtils.toJsonNode(body));
		success.setCode(servletRespose.getStatus());
		return success;
	}

	@Override
	public int getOrder() {
		return Integer.MIN_VALUE + 10;
	}

}